package com.quectel.cms.controller.prewarning;

import com.quectel.cms.controller.BaseController;
import com.quectel.cms.vo.prewarning.PreWarningConfigVo;
import com.quectel.constant.core.PreWarnConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.prewarning.dto.PreWarningConfigDto;
import com.quectel.core.module.prewarning.service.PreWarningConfigService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2021-11-29 13:13:54
 */
@RestController
@RequestMapping("preWarningConfig")
@Tag(name = "PreWarningConfigController", description = "智能预警规则配置相关api")
public class PreWarningConfigController extends BaseController {

    @DubboReference
    private PreWarningConfigService preWarningConfigService;
    @DubboReference
    private VillageService villageService;

    /**
     * 查询每个小区下的智能预警规则配置情况
     *
     * @return
     */
    @GetMapping("queryVillageConfig")
    @Operation(summary = "查询每个小区下的智能预警规则配置情况")
    public Response<Page<PreWarningConfigVo>> queryVillageConfig() {
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = villageService.queryTotal(request.getParams());

        List<PreWarningConfigVo> resultList = new ArrayList<>();
        List<VillageDto> villageDtos = null;
        if (total > 0) {
            villageDtos = villageService.queryList(request.getParams());
            for (VillageDto villageDto : villageDtos) {
                PreWarningConfigVo configVo = new PreWarningConfigVo();
                configVo.setVillageId(villageDto.getId());
                configVo.setVillageName(villageDto.getName());
                configVo.setVillageCode(villageDto.getCode());

                // 久出未归
                PreWarningConfigDto longOutNoIn = preWarningConfigService.selectOne(villageDto.getId(), PreWarnConstants.AlarmTypeEnum.LONG_OUT_NO_IN.getType());
                if (longOutNoIn != null) {
                    configVo.setPreWarningTypeOne(longOutNoIn.getStatus());
                } else {
                    configVo.setPreWarningTypeOne(PreWarnConstants.AlarmStatusEnum.NO_SETTING.getStatus());
                }

                // 久归未出
                PreWarningConfigDto longInNoOut = preWarningConfigService.selectOne(villageDto.getId(), PreWarnConstants.AlarmTypeEnum.LONG_IN_NO_OUT.getType());
                if (longInNoOut != null) {
                    configVo.setPreWarningTypeTwo(longInNoOut.getStatus());
                } else {
                    configVo.setPreWarningTypeTwo(PreWarnConstants.AlarmStatusEnum.NO_SETTING.getStatus());
                }

                // 久归未出
                PreWarningConfigDto carRecordTopoMany = preWarningConfigService.selectOne(villageDto.getId(), PreWarnConstants.AlarmTypeEnum.CAR_RECORD_TOO_MANY.getType());
                if (carRecordTopoMany != null) {
                    configVo.setPreWarningTypeThree(carRecordTopoMany.getStatus());
                } else {
                    configVo.setPreWarningTypeThree(PreWarnConstants.AlarmStatusEnum.NO_SETTING.getStatus());
                }

                resultList.add(configVo);
            }
        } else {
            resultList = new ArrayList<>();
        }

        Page<PreWarningConfigVo> page = new Page<>(request.getPageNo(), request.getPageSize(), total, resultList);
        return Response.<Page<PreWarningConfigVo>>ok().wrap(page);
    }

    /**
     * 根据条件查询智能预警规则配置无分页列表
     *
     * @return
     */
    @GetMapping("getListByParam")
    @Operation(summary = "根据条件查询智能预警规则配置无分页列表")
    public Response<List<PreWarningConfigDto>> getListByParam() {
        Request request = Request.configParams(Request.parseParams(httpServletRequest));
        List<PreWarningConfigDto> list = preWarningConfigService.queryList(request.getParams());
        return Response.<List<PreWarningConfigDto>>ok().wrap(list);
    }

    /**
     * 批量保存智能预警规则配置记录
     */
    @PostMapping("batchSaveOrEdit")
    @Operation(summary = "批量保存智能预警规则配置记录")
    public Response<Object> batchSaveOrEdit(@RequestBody List<PreWarningConfigDto> dtoList) {

        for (PreWarningConfigDto preWarningConfigDto : dtoList) {
            //填充基础数据
            fillSaveCommonData(preWarningConfigDto);
        }

        for (int i = 0; i < dtoList.size(); i++) {
            Long id = dtoList.get(i).getId();
            Byte preWarnType = dtoList.get(i).getPreWarnType();
            // id不存在 save
            if (id == null && PreWarnConstants.AlarmTypeEnum.LONG_OUT_NO_IN.getType().equals(preWarnType)) {
                PreWarningConfigDto preWarningConfigDto = dtoList.get(i);
                preWarningConfigService.save(preWarningConfigDto);
            } else {
                PreWarningConfigDto preWarningConfigDto = dtoList.get(i);
                preWarningConfigDto.setEditTime(new Date());
                preWarningConfigService.updateById(preWarningConfigDto);
            }

            if (id == null && PreWarnConstants.AlarmTypeEnum.LONG_IN_NO_OUT.getType().equals(preWarnType)) {
                PreWarningConfigDto preWarningConfigDto = dtoList.get(i);
                preWarningConfigService.save(preWarningConfigDto);
            } else {
                PreWarningConfigDto preWarningConfigDto = dtoList.get(i);
                preWarningConfigDto.setEditTime(new Date());
                preWarningConfigService.updateById(preWarningConfigDto);
            }

            if (id == null && PreWarnConstants.AlarmTypeEnum.CAR_RECORD_TOO_MANY.getType().equals(preWarnType)) {
                PreWarningConfigDto preWarningConfigDto = dtoList.get(i);
                preWarningConfigService.save(preWarningConfigDto);
            } else {
                PreWarningConfigDto preWarningConfigDto = dtoList.get(i);
                preWarningConfigDto.setEditTime(new Date());
                preWarningConfigService.updateById(preWarningConfigDto);
            }
        }
        return Response.ok();
    }


    /**
     * 根据条件查询智能预警规则配置分页查询列表
     */
    @GetMapping("list")
    @RequirePermissions(values = "preWarningConfig:list")
    @Operation(summary = "根据条件查询智能预警规则配置分页查询列表")
    public Response<Page<PreWarningConfigDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = preWarningConfigService.queryTotal(request.getParams());

        List<PreWarningConfigDto> list = null;
        if (total > 0) {
            list = preWarningConfigService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<PreWarningConfigDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<PreWarningConfigDto>>ok().wrap(page);
    }


    /**
     * 查询智能预警规则配置单条记录
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "preWarningConfig:info")
    @Operation(summary = "查询智能预警规则配置单条记录")
    public Response<PreWarningConfigDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (preWarningConfigService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        PreWarningConfigDto preWarningConfigDto = preWarningConfigService.selectById(id);

        return Response.<PreWarningConfigDto>ok().wrap(preWarningConfigDto);
    }

    /**
     * 保存智能预警规则配置单条记录
     */
    @PostMapping("save")
    @RequirePermissions(values = "preWarningConfig:edit")
    @Operation(summary = "保存智能预警规则配置单条记录")
    public Response<Object> save(@RequestBody @Validated PreWarningConfigDto preWarningConfigDto) {

        //填充基础数据
        fillSaveCommonData(preWarningConfigDto);

        preWarningConfigService.save(preWarningConfigDto);

        return Response.ok();
    }

    /**
     * 修改智能预警规则配置单条记录
     */
    @PostMapping("update")
    @RequirePermissions(values = "preWarningConfig:edit")
    @Operation(summary = "修改智能预警规则配置单条记录")
    public Response<Object> update(@RequestBody @Validated PreWarningConfigDto preWarningConfigDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(preWarningConfigDto.getId()));
        if (preWarningConfigService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(preWarningConfigDto);

        preWarningConfigService.updateById(preWarningConfigDto);

        return Response.ok();
    }

    /**
     * 批量删除智能预警规则配置单条记录
     */
    @PostMapping("delete")
    @RequirePermissions(values = "preWarningConfig:delete")
    @Operation(summary = "批量删除智能预警规则配置单条记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (preWarningConfigService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        preWarningConfigService.deleteBatch(ids);

        return Response.ok();
    }
}
